package com.gandong8.trace.tool.util;



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
    private static final String PATTERN_DEFAULT = "yyyy-MM-dd HH:mm:ss";
    private static final String PATTERN_YMD = "yyyy-MM-dd";
    private static final String PATTERN_HIS = "HH:mm:ss";

    public static String format(Date date) {
       return format(date, null);
    }

    public static String format(Date date, String pattern) {
        SimpleDateFormat formatter = getDateFormat(pattern);
        return formatter.format (date);
    }

    public static Date parse(String dateStr) {
        return parse(dateStr, null);
    }

    public static Date parse(String dateStr, String pattern) {
        SimpleDateFormat dateFormat = getDateFormat(pattern);
        try {
            return dateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static SimpleDateFormat getDateFormat(String pattern) {
        if(pattern == null) {
            pattern = PATTERN_DEFAULT;
        }
        //SimpleDateFormat不是线程安全的,每次解析时需要重新new一下
        //或者可以使用joda-time库里的DateTimeFormatter
        return new SimpleDateFormat (pattern);
    }
}
